package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {



    @Autowired
    private  WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    public UserServiceImpl(WeChatProperties weChatProperties) {
        this.weChatProperties = weChatProperties;
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {

        //创建
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        Map<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("appid", weChatProperties.getAppid());
        paraMap.put("secret", weChatProperties.getSecret());

        paraMap.put("js_code", userLoginDTO.getCode());
        paraMap.put("grant_type", "authorization_code");

        String res = httpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paraMap);
        JSONObject response = JSON.parseObject(res);
        log.info("http返回对象：{}", response);
        //主要获取的是openid微信身份证
        String openid = response.getString("openid");

        //连openid微信都没有注册
        if (openid == null) {
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }

        //通过openid查询用户
         User user = userMapper.selectUserByOpenid(openid);

         if (user == null) {
              user = User.builder()
                     .openid(openid)
                     .createTime(LocalDateTime.now())
                      .name(openid.substring(0,5))
                     .build();
              userMapper.insert(user);
         }


        return user;
    }
}
